package com.example.meituan.activity.user;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.example.meituan.R;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.ImgBean;
import com.example.meituan.activity.bean.ShopBean;
import com.example.meituan.activity.bean.ShopCarBean;
import com.example.meituan.activity.bean.TypeBean;
import com.example.meituan.activity.bean.UserAddressBean;
import com.example.meituan.activity.user.adapter.ProductAdapter;
import com.example.meituan.activity.user.adapter.typeAdapter;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.dao.ImgDao;
import com.example.meituan.dao.ShopCarDao;
import com.example.meituan.dao.ShopDao;
import com.example.meituan.dao.TypeDao;
import com.example.meituan.dao.UserAddressDao;
import com.example.meituan.dao.UserDao;

import java.io.File;
import java.util.List;
import java.util.UUID;

public class ProductDetailsBottomSheetDialog extends DialogFragment implements onItemClick {

    private ProductDetailsBottomSheetDialogListener listener;
    private TextView quantityTextView,price,choose,address; // 数量的 TextView
    private ShopBean shopBean;// 存储 ShopBean 实例
    private TypeBean typeBean;
    ImageView shopImg,exit;
    List<TypeBean> types;
    androidx.recyclerview.widget.RecyclerView recyclerView;
    int quantity;
    AdminBean currentUser;
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_layout, null);

        // 初始化视图
        quantityTextView = view.findViewById(R.id.number_shop_car);
         shopImg=view.findViewById(R.id.shop_car_img);
         price=view.findViewById(R.id.shop_car_price_sheet);
        recyclerView=view.findViewById(R.id.shop_car_type_recyclerView);
        choose=view.findViewById(R.id.shop_car_choose);
        exit=view.findViewById(R.id.exit_shop_car);
        address=view.findViewById(R.id.shop_car_address);
        quantity=1;
        // 设置初始值
        if (shopBean != null) {
            createTypeButtons();
            initializeViews();
        }

        // 设置点击监听器
        setClickListeners(view);

        return builder.setView(view).create();
    }

    private void initializeViews() {
        // 假设 ShopBean 包含数量、价格和默认重量信息
        currentUser=AdminDao.getUserInfo(getActivity());
        quantityTextView.setText(quantity+"");
        List<ImgBean>imgBeans= ImgDao.getAllImagesByShopId(shopBean.getId());
        if (imgBeans != null && !imgBeans.isEmpty()) {
            ImgBean firstImgBean = imgBeans.get(0);
            String imagePath = firstImgBean.getImg();

            File imageFile = new File(imagePath);
            if (imageFile.exists()) {

                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                if (bitmap != null) {
                    shopImg.setImageBitmap(bitmap);
                }
            }
        }
        price.setText("¥"+shopBean.getPrice());
        choose.setText("已选: "+shopBean.getName()+"("+types.get(0).getTypeDescription()+")");
        List<UserAddressBean> userAddressList = UserAddressDao.getUserAddressesByUserId(currentUser.getUserId());
        if (userAddressList!=null&&userAddressList.size()>0){
            address.setText(userAddressList.get(0).getS_address());
        }else {
            address.setText("-");
        }

    }

    private void createTypeButtons() {
         types = TypeDao.getAllTypesByShopId(shopBean.getId()); // 获取所有类型
        if (types == null || types.isEmpty()) {
            Toast.makeText(getContext(), "没有数据显示", Toast.LENGTH_SHORT).show();
            recyclerView.setAdapter(null);
        } else {
            typeAdapter adapter = new typeAdapter(types,ProductDetailsBottomSheetDialog.this);
            recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),5));
            recyclerView.setAdapter(adapter);
        }

    }




    private void setClickListeners(View view) {
        // 找到加减按钮并设置监听器
        view.findViewById(R.id.minus_shop_car).setOnClickListener(v -> {
            if (quantity > 1) { // 使用 ShopBean 中的最小数量
                quantity--;
                updateQuantityView();
            }
        });

        view.findViewById(R.id.add_shop_car).setOnClickListener(v -> {
                quantity++;
                updateQuantityView();
        });

        view.findViewById(R.id.add_shop_car_sheet).setOnClickListener(v -> {
            ShopCarBean shopCarBean=new ShopCarBean();
            currentUser= AdminDao.getUserInfo(view.getContext());
            shopCarBean.setsUserId(currentUser.getUserId());
            shopCarBean.setsShopId(shopBean.getId());
            shopCarBean.setsTime(System.currentTimeMillis());
            shopCarBean.setsType(typeBean==null?"":typeBean.getTypeDescription());
            String id= UUID.randomUUID().toString().replace("-","");
            shopCarBean.setsId(id);
            int a=ShopCarDao.insert(shopCarBean);
            if(a==1){
                Toast.makeText(view.getContext(), "购物车添加成功",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(view.getContext(),"购物车添加失败",Toast.LENGTH_SHORT).show();
            }
        });

        view.findViewById(R.id.exit_shop_car).setOnClickListener(v->{
            if (listener != null) {
                listener.exit();
            }
        });
    }

    private void updateQuantityView() {
        quantityTextView.setText(String.valueOf(quantity));
    }

    public void show(ProductDetailsBottomSheetDialogListener listener, ShopBean shopBean, androidx.fragment.app.FragmentManager fragmentManager) {
        this.listener = listener;
        this.shopBean = shopBean;
        super.show(fragmentManager, "product_details");
    }

    @Override
    public void onItemClick(TypeBean type) {
        typeBean=type;
        choose.setText("已选: "+shopBean.getName()+"("+type.getTypeDescription()+")");
    }

    public interface ProductDetailsBottomSheetDialogListener {
        void exit();
    }

}
